﻿using Autofac;
using HZH_Controls.Controls;
using System.Data;
using Tulpep.NotificationWindow;
using WinformDevFramework;
using WinformDevFramework.IServices;
using WinformDevFramework.IServices.System;
using WinformDevFramework.Models;
//using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace WinformDevFarme
{
    public partial class FrmMain : Form
    {
        private Point mPoint;
        private ISysMenuServices _sysMenuServices;
        private IsysMessageServices _sysMessageServices;
        public FrmMain(ISysMenuServices sysMenuServices, IsysMessageServices sysMessageServices)
        {
            _sysMenuServices = sysMenuServices;
            _sysMessageServices = sysMessageServices;
            InitializeComponent();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnMin_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void btnMax_Click(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Maximized)
            {
                this.WindowState = FormWindowState.Normal;
            }
            else
            {
                this.WindowState = FormWindowState.Maximized;
            }
        }

        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            mPoint=new Point(e.X, e.Y);
        }

        private void panel1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Location = new Point(this.Location.X + e.X - mPoint.X, this.Location.Y + e.Y - mPoint.Y);
            }
        }

        private void InitData()
        {
            //设置当前用户名
            lblUsername.Text = AppInfo.User.Fullname;

            //初始化导航菜单
            var menus = AppInfo.UserMenus.Where(p => p.MenuType.Equals("Page")); // 只考虑表单类型的菜单项
            foreach (var menu in menus)
            {
                TabPage tabPage = new TabPage(menu.Title);
                tabPage.Name = menu.URL; // 使用菜单项的URL作为标签页的名称
                tabPage.Tag = menu.ID; // 存储菜单项的ID作为标签页的标签（可选）

                // 这里可以选择加载表单到标签页，或者延迟加载直到用户选择标签页
                // Form childForm = AppInfo.Container.ResolveNamed<Form>(menu.URL);
                // childForm.Dock = DockStyle.Fill;
                // tabPage.Controls.Add(childForm);

                tabControl2.TabPages.Add(tabPage);
            }

            // 设置默认的标签页
            if (tabControl2.TabPages.Count > 0)
            {
                tabControl2.SelectedTab = tabControl2.TabPages[0];
                // 调用事件处理函数
                TabControl2_SelectedIndexChanged(this, EventArgs.Empty);
            }

            // 订阅 TabControl 的 SelectedIndexChanged 事件
            tabControl2.SelectedIndexChanged += TabControl2_SelectedIndexChanged;
        }

        // 事件处理函数
        private void TabControl2_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 获取当前选中的 TabPage
            TabPage selectedTab = tabControl2.SelectedTab;
            if (selectedTab != null)
            {
               

                // 根据 TabPage 的 Name（即菜单项的 URL）来加载相应的表单
                string url = selectedTab.Name;

                // 移除当前 TabPage 中可能存在的旧表单
                selectedTab.Controls.Clear();

                //// 创建一个新的 Panel
                //Panel panel = new Panel
                //{
                //    Dock = DockStyle.Fill // 让 Panel 填充整个 TabPage
                //};

                // 创建一个新的 FlowLayoutPanel
                FlowLayoutPanel flowLayoutPanel = new FlowLayoutPanel
                {
                    Dock = DockStyle.Fill, // 让 FlowLayoutPanel 填充整个 TabPage
                    FlowDirection = FlowDirection.LeftToRight, // 设置为从(上到下排列TopDown)（左到右 LeftToRight 或其他方向）
                    AutoScroll = true, // 如果按钮太多以至于不能全部显示，则启用滚动条
                    WrapContents = false // 如果按钮在一行内排满后再换行，则设置为 true；否则，每个按钮都会占据一行
                };
                selectedTab.Controls.Add(flowLayoutPanel);//添加到tab

                var menuid = selectedTab.Tag;
                if (menuid!=null)
                {
                    var menus = AppInfo.UserMenus.Where(p => p.ParentID.Equals(menuid));//根据id筛选
                    //ImageList imageList = new ImageList();
                    foreach (var menu in menus)
                    {
                        Button btn = new Button
                        {
                            Text = menu.Title, // 使用Form的标题作为按钮文本
                            Image = Image.FromFile(Application.StartupPath + "\\" + menu.Icon), // 设置按钮的图像
                            Tag = menu.ID, // 使用Form的ID作为按钮的标签，以便在点击时识别
                            FlatStyle = FlatStyle.Flat,
                            Font = new Font("Microsoft YaHei UI", 10.5F, FontStyle.Bold, GraphicsUnit.Point),
                            Location = new Point(0, 0),
                            Name = "button1",
                            Size = new Size(103, 61),
                            TabIndex = 1,
                            TextAlign = ContentAlignment.BottomCenter,
                            TextImageRelation = TextImageRelation.ImageAboveText,
                            UseVisualStyleBackColor = true,
                        };
                        // 为按钮添加点击事件处理程序,跳转到设置相应的 URL 页面
                        btn.Click += (s, args) =>
                        {
                            // 在这里处理按钮点击事件
                            // 可以使用 (s as Button)?.Tag 来获取按钮的标签（即 menu.ID）
                            var childForm = AppInfo.Container.ResolveNamed<Form>(menu.URL);
                            childForm.TopLevel = false;
                            childForm.FormBorderStyle = FormBorderStyle.None;
                            childForm.Dock = DockStyle.Fill;
                            childForm.Tag=menu.ID;
                            if (tabControl1.TabPages[menu.URL] == null)
                            {
                                TabPage page = new TabPage(menu.Title);
                                page.Name = menu.URL;
                                page.Controls.Add(childForm);
                                tabControl1.TabPages.Add(page);
                                tabControl1.SelectedTab = page;

                                childForm.Show();
                            }
                            else
                            {
                                tabControl1.SelectedTab = tabControl1.TabPages[menu.URL];
                            }
                        };

                        //// 将按钮添加到 Panel 中
                        //panel.Controls.Add(btn);
                        flowLayoutPanel.Controls.Add(btn);

                    }
                    // 将 Panel 添加到 TabPage 中
                    //selectedTab.Controls.Add(panel);

                }
            }
        }

        /// <summary>
        /// 窗体加载完成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmMain_Load(object sender, EventArgs e)
        {
            InitData();
            //tabControl1.DrawMode = TabDrawMode.OwnerDrawFixed;
            //tabControl1.Padding = new System.Drawing.Point(CLOSE_SIZE, CLOSE_SIZE / 2);
            //tabControl1.DrawItem+=new DrawItemEventHandler(MainTabControl_DrawItem);
            //tabControl1.MouseDown+=new System.Windows.Forms.MouseEventHandler(MainTabControl_MouseDown);
            //tabControl1.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.MainTabControl_MouseDoubleClick);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            lblDatetime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            List<sysMessage> messages = _sysMessageServices.QueryListByClause(p => p.IsSend == false && p.ToUserID == AppInfo.User.ID);
            foreach (var message in messages)
            {
                // 创建一个PopupNotifier实例
                PopupNotifier popup = new PopupNotifier();
                popup.Size = new Size(300, 500);
                popup.TitleText = message.Title;
                popup.ContentText = message.Content;

                // 设置通知的样式和位置
                popup.AnimationDuration = 500;
                popup.Delay = 3000;
                popup.AnimationInterval = 20;
                popup.Popup();

                message.IsSend = true;
                message.SendTime=DateTime.Now;
                _sysMessageServices.Update(message);
            }
        }


        const int CLOSE_SIZE = 9;
        /// <summary>
        /// 绘制“Ｘ”号即关闭按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainTabControl_DrawItem(object sender, DrawItemEventArgs e)
        {
            try
            {
                Rectangle myTabRect = this.tabControl1.GetTabRect(e.Index);

                //先添加TabPage属性     
                e.Graphics.DrawString(this.tabControl1.TabPages[e.Index].Text
                , this.Font, SystemBrushes.ControlText, myTabRect.X + 2, myTabRect.Y + 2);

                //再画一个矩形框  
                using (Pen p = new Pen(Color.White))
                {
                    myTabRect.Offset(myTabRect.Width - (CLOSE_SIZE + 3), 2);
                    myTabRect.Width = CLOSE_SIZE;
                    myTabRect.Height = CLOSE_SIZE;
                    e.Graphics.DrawRectangle(p, myTabRect);

                }

                //填充矩形框  
                Color recColor = e.State == DrawItemState.Selected ? Color.White : Color.White;
                using (Brush b = new SolidBrush(recColor))
                {
                    e.Graphics.FillRectangle(b, myTabRect);
                }

                //画关闭符号  
                using (Pen objpen = new Pen(Color.Black))
                {
                    //"\"线  
                    Point p1 = new Point(myTabRect.X + 3, myTabRect.Y + 3);
                    Point p2 = new Point(myTabRect.X + myTabRect.Width - 3, myTabRect.Y + myTabRect.Height - 3);
                    e.Graphics.DrawLine(objpen, p1, p2);

                    //"/"线  
                    Point p3 = new Point(myTabRect.X + 3, myTabRect.Y + myTabRect.Height - 3);
                    Point p4 = new Point(myTabRect.X + myTabRect.Width - 3, myTabRect.Y + 3);
                    e.Graphics.DrawLine(objpen, p3, p4);
                }

                e.Graphics.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 关闭按钮功能  
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainTabControl_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                int x = e.X, y = e.Y;

                //计算关闭区域     
                Rectangle myTabRect = this.tabControl1.GetTabRect(this.tabControl1.SelectedIndex);

                myTabRect.Offset(myTabRect.Width - (CLOSE_SIZE + 3), 2);
                myTabRect.Width = CLOSE_SIZE;
                myTabRect.Height = CLOSE_SIZE;

                //如果鼠标在区域内就关闭选项卡     
                bool isClose = x > myTabRect.X && x < myTabRect.Right
                 && y > myTabRect.Y && y < myTabRect.Bottom;

                if (isClose == true)
                {
                    this.tabControl1.TabPages.Remove(this.tabControl1.SelectedTab);
                }
            }
        }

        /// <summary>
        /// 双击关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainTabControl_MouseDoubleClick(object sender, EventArgs e)
        {
            tabControl1.TabPages.Remove(tabControl1.SelectedTab);
        }
    }
}
